﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.Authorizations
{
    /// <summary>
    /// 定义自定义认证特性类
    /// </summary>
    public class MinimumAgeAuthorizeAttribute : AuthorizeAttribute
    {
        // 策略名前缀
        public const string PolicyPrefix = "MinimumAge";

        // 通过构造函数传入最小年龄
        public MinimumAgeAuthorizeAttribute(int minimumAge) =>
            MinimumAge = minimumAge;

        public int MinimumAge
        {
            get
            {
                // 从策略名中解析出最小年龄
                if (int.TryParse(Policy[PolicyPrefix.Length..], out var age))
                {
                    return age;
                }

                return default;
            }
            set
            {
                // 生成动态的策略名，如 MinimumAge18 表示最小年龄为18的策略
                Policy = $"{PolicyPrefix}{value}";
            }
        }
    }
}
